package com.atguigu.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.client.OrderFeignClient;
import com.atguigu.config.AlipayConfig;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.enums.PaymentStatus;
import com.atguigu.enums.PaymentType;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.mapper.PaymentInfoMapper;
import com.atguigu.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 支付信息表 服务实现类
 * </p>
 *
 * @author linjiang
 * @since 2022-08-09
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public String createQrCode(Long orderId) throws AlipayApiException {
        OrderInfo orderInfo = orderFeignClient.getOrder(orderId);
        //保存支付信息
        savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //支付成功之后的异步通知 支付宝调用我们的商户系统
        request.setReturnUrl(AlipayConfig.return_payment_url);
        //支付成功之后支付宝会调用我们的payment微服务
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("total_amount", orderInfo.getTotalMoney());
        bizContent.put("subject", "天太热了，买个西瓜");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //请求参数的集合
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            String alipayHtml = response.getBody();
            return alipayHtml;
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo) {
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("out_trade_no",outTradeNo);
        //支付方式
        wrapper.eq("payment_type",PaymentType.ALIPAY.name());
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public void updatePaymentInfo(String outTradeNo, String paymentTypeName, Map<String, String> aliPayParam) {
         //修改支付订单表 状态 回调时间 交易号
        PaymentInfo paymentInfo = getPaymentInfo(outTradeNo);
        paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
        paymentInfo.setTradeNo(outTradeNo);
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(aliPayParam.toString());

        baseMapper.updateById(paymentInfo);
        //更新订单信息 需要在订单系统shop-order中编写代码
        rabbitTemplate.convertAndSend(MqConst.PAY_ORDER_EXCHANGE,MqConst.PAY_ORDER_ROUTE_KEY,paymentInfo.getOrderId());
    }


    private void savePaymentInfo(OrderInfo orderInfo, String paymentTypeName) {
        //为了防止重复点击
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
       wrapper.eq("order_id",orderInfo.getId());
       wrapper.eq("payment_type",paymentTypeName);
        Integer count = baseMapper.selectCount(wrapper);
        if(count>1){
            //直接结束 不保存
            return;
        }
        //创建一个paymentInfo 对象
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setOrderId(orderInfo.getId().toString());
        paymentInfo.setPaymentType(paymentTypeName);
        paymentInfo.setPaymentMoney(orderInfo.getTotalMoney());
        paymentInfo.setPaymentContent(orderInfo.getTradeBody());
        paymentInfo.setPaymentStatus(orderInfo.getOrderStatus());
        paymentInfo.setCreateTime(new Date());
        baseMapper.insert(paymentInfo);
    }


    @Override
    public boolean reFundAliPayTrade(Long orderId) throws AlipayApiException {
        OrderInfo orderInfo = orderFeignClient.getOrder(orderId);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("refund_amount",orderInfo.getTotalMoney());
        bizContent.put("out_request_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            PaymentInfo paymentInfo = getPaymentInfo(orderInfo.getOutTradeNo());
            paymentInfo.setPaymentStatus(PaymentStatus.ClOSED.name());
            baseMapper.updateById(paymentInfo);
            System.out.println("订单交易退款调用成功");
            return true;
        }
            System.out.println("订单交易退款调用失败");
            return false;
    }

    @Override
    public boolean queryAliPayTrade(Long orderId) throws AlipayApiException {
        OrderInfo orderInfo = orderFeignClient.getOrder(orderId);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean closeAliPayTrade(Long orderId) throws AlipayApiException {
        OrderInfo orderInfo = orderFeignClient.getOrder(orderId);
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("关闭订单接口调用成功");
            return true;
        }
        System.out.println("关闭订单接口调用失败");
        return false;
    }
}
